#include "limbo/errc.h"
#include "limbo/icmp/echo_request.hpp"
#include "limbo/icmp/echo_response.hpp"
#include "limbo/icmp/state.hpp"
#include "limbo/ip/state.hpp"
#include "limbo/slip/state.hpp"
#include "limbo/udp/connection.hpp"
#include "limbo/udp/receiver.hpp"
#include "limbo/udp/state.hpp"

#include "limbo/stack.hpp"
#include "test-utils.h"

using namespace limbo;

using SLIP = slip::State<void>;
using IP = ip::State<SLIP>;
using ICMP = icmp::State<IP>;
using UDP = udp::State<IP>;
using EchoReq = icmp::EchoRequest<ICMP>;
using EchoRes = icmp::EchoResponse<ICMP>;
using Receiver = udp::Receiver<UDP>;
using Connection = udp::Connection<UDP>;

using MyStack = Stack<Layer<Connection, Receiver, EchoReq, EchoRes>, /* app */
                      Layer<UDP, ICMP>, /* transport */
                      Layer<IP>,        /* network */
                      Layer<SLIP>       /* link */
                      >;

auto src = make_address("169.254.1.1");
auto dst = make_address("169.254.1.2");

unsigned char payload_raw[] = {
    0x8b, 0x15, 0x51, 0x63, 0x00, 0x00, 0x00, 0x00, 0x1a, 0x4c, 0x09, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
    0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23,
    0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
    0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
};
auto payload = Chunk(payload_raw, sizeof(payload_raw));

TEST_CASE("send + receive", "[scenario]") {
  MyStack stack_1, stack_2;
  auto &echo_req_1 = stack_1.get<0, 2>();
  auto &echo_req_2 = stack_2.get<0, 2>();

  char buff_raw[128];
  auto buff = Chunk(buff_raw, sizeof(buff_raw));

  echo_req_1.init(src, 64, 0x5DDE, 0x47);
  echo_req_2.init(dst, 64, 0x5DDE, 0x47);
  auto tx_result = echo_req_1.send(stack_1, buff, dst, payload);
  REQUIRE(tx_result);

  auto rx_result = stack_2.recv(tx_result.consumed(), nullptr);
  REQUIRE(rx_result);
  REQUIRE(!rx_result.demand());
  REQUIRE(rx_result.state() == &echo_req_2);
  auto p = echo_req_2.get_parsed();
  CHECK(p.payload == payload);
}
